package customer

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"git.mycaigou.com/gfyx/common/http_client"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/common/usermetadata"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	customerDto "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/dto/customer"
	opptyStatusRepo "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/business_opportunity/oppty_status"
	subscriptionRepo "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/business_opportunity/subscription/radar"
	customerRepo "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/clue/customer"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/remote/bigdata_remote"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/remote/openapi_remote"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/remote/opensearch_remote"
	pb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"strings"
)

type businessCustomerService struct {
	openSearchRepos              opensearch_remote.OpenSearchRepositoryIface
	opptyStatusRepos             opptyStatusRepo.GfyxOpptyStatusReposIface
	customerRepo                 customerRepo.CustomerManageRepositoryIface
	bigDataServiceRepo           bigdata_remote.BigDataServiceRepositoryIface
	openApiRepo                  openapi_remote.OpenApiRepoIface
	radarSubscriptionConfigRepos subscriptionRepo.GfyxRadarSubscriptionConfigReposIface
}

func NewBusinessCustomerService(
	openSearchRepos opensearch_remote.OpenSearchRepositoryIface,
	opptyStatusRepos opptyStatusRepo.GfyxOpptyStatusReposIface,
	customerRepo customerRepo.CustomerManageRepositoryIface,
	bigDataServiceRepo bigdata_remote.BigDataServiceRepositoryIface,
	openApiRepo openapi_remote.OpenApiRepoIface,
	radarSubscriptionConfigRepos subscriptionRepo.GfyxRadarSubscriptionConfigReposIface,
) CustomerServiceIface {
	return &businessCustomerService{
		openSearchRepos:              openSearchRepos,
		opptyStatusRepos:             opptyStatusRepos,
		customerRepo:                 customerRepo,
		bigDataServiceRepo:           bigDataServiceRepo,
		openApiRepo:                  openApiRepo,
		radarSubscriptionConfigRepos: radarSubscriptionConfigRepos,
	}
}

func (s *businessCustomerService) SearchCustomerList(ctx context.Context, request *pb.SearchCustomerListRequest) (*pb.SearchCustomerListResponse, error) {
	resp := &pb.SearchCustomerListResponse{}

	searchRequest := &opensearch_remote.GetCustomerListRequest{
		Keyword:             request.Keyword,
		CompanyNameKeyword:  request.CompanyNameKeyword,
		CompanyIdentity:     request.CompanyIdentity,
		CompanyArea:         request.AreaCodes,
		CompanyLevel:        request.CompanyLevel,
		CompanyLabel:        request.CompanyLabel,
		CompanyType:         request.CompanyType,
		IndustryCategory:    request.IndustryCategory,
		LandUsageLabel:      request.LandUsageLabel,
		ProjectTypeLabel:    request.ProjectTypeLabel,
		FitmentFeeLabel:     request.FitmentFeeLabel,
		BiddingArea:         request.BiddingArea,
		CreditLevel:         request.CreditLevel,
		ProjectProvinceCode: request.ProjectProvinceCode,
		ProjectCityCode:     request.ProjectCityCode,
		ProjectBeginDate:    request.ProjectBeginDate,
		ProjectEndDate:      request.ProjectEndDate,
		Page:                request.Page,
		PageSize:            request.PageSize,
	}
	searchData, err := s.openSearchRepos.GetCustomerList(ctx, searchRequest)
	if err != nil {
		return nil, err
	}

	if searchData == nil {
		return resp, nil
	}

	resp.Total = searchData.Total
	var customerOrganizingCodeList []string
	for _, item := range searchData.List {
		customerOrganizingCodeList = append(customerOrganizingCodeList, item.OrganizingCode)

		customerPbItem := openSearchCustomerDetail2pbDetail(item)
		resp.List = append(resp.List, customerPbItem)
	}

	metaUserInfo := usermetadata.GetMetaUserInfo(ctx)
	opptyStatusPoList, _ := s.opptyStatusRepos.GetOpptyStatusBatch(ctx, constants.OpptySourceCustomer, customerOrganizingCodeList, metaUserInfo.TenantUserUid)

	opptyStatusMap := make(map[string]string)
	for _, opptyStatusPo := range opptyStatusPoList {
		opptyStatusMap[opptyStatusPo.DataSourceId] = constants.GetOpptyNameByStatus(opptyStatusPo.Status)
	}

	_, existCustomerList, _ := s.customerRepo.QuerySimpleCustomerList(ctx, map[string]interface{}{"organizing_codes": customerOrganizingCodeList, "is_deleted": constants.IsDeletedFalse}, nil)
	existCustomerMap := make(map[string]bool)
	for _, customerPo := range existCustomerList {
		existCustomerMap[customerPo.OrganizingCode] = true
	}

	for _, item := range resp.List {
		if opptyStatusName, ok := opptyStatusMap[item.OrganizingCode]; ok {
			item.OpptyStatus = opptyStatusName
		}

		if _, ok := existCustomerMap[item.OrganizingCode]; ok {
			item.IsExistCustomer = true
		}
	}

	return resp, nil
}

func openapiCustomerDetail2pbDetail(item *openapi_remote.CompanyDetailBo) *pb.CustomerDetail {
	if item == nil {
		return nil
	}

	return &pb.CustomerDetail{
		CompanyName:                      item.CompanyName,
		CompanyNameHl:                    item.CompanyName,
		OrganizingCode:                   item.OrganizingCode,
		CompanyLogo:                      "",
		BusinessStatusLabel:              item.BusinessStatus,
		TopCompanyName:                   "",
		TopCompanyOrganizingCode:         "",
		CompanyIdentity:                  make([]string, 0),
		CompanyType:                      "",
		CompanyLevel:                     make([]*pb.CustomerLabel, 0),
		CompanyLabel:                     make([]*pb.CustomerLabel, 0),
		Province:                         item.Province,
		City:                             item.City,
		LegalName:                        item.LegalName,
		RegistCapi:                       item.RegistCapi,
		EstablishDate:                    item.StartDate,
		IndustryCategory:                 item.MainIndustry,
		BidCnt_2Year:                     0,
		TakeLandCnt_2Year:                0,
		CommencePermitCnt_2Year:          0,
		SellProjectCnt_2Year:             0,
		CooperationCaseCnt_2Year:         0,
		ContactNum:                       0,
		CustomerDynamic:                  nil,
		IsExistCustomer:                  false,
		OpptyStatus:                      "",
		Telephone:                        item.PhoneNumber,
		BidCnt_1Year:                     0,
		TakeLandCnt_1Year:                0,
		CommencePermitCnt_1Year:          0,
		SellProjectCnt_1Year:             0,
		CooperationCaseCnt_1Year:         0,
		Scope:                            item.Scope,
		EnterpriseNature:                 "",
		TermStart:                        item.TermStart,
		TermEnd:                          item.TermEnd,
		RecCapi:                          item.RecCap,
		NumberOfEmployees:                item.NumberOfEmployees,
		Address:                          item.Address,
		BidNum:                           0,
		ProjectNum:                       0,
		CooperationEnterpriseNum:         0,
		CooperationProjectNum:            0,
		CompanyProfile:                   "",
		OldCompanyNameHl:                 "",
		TakeLandNum:                      0,
		CommencePermitNum:                0,
		SellProjectNum:                   0,
		EsScore:                          0,
		ProvinceCode:                     item.ProvinceCode,
		CityCode:                         item.CityCode,
		CreditLevel:                      "",
		ProjectNameHl:                    "",
		BidCntWithArea_2Year:             0,
		LandCntWithArea_2Year:            0,
		CommencePermitCntWithArea_2Year:  0,
		SellProjectCntWithArea_2Year:     0,
		CooperationCaseCntWithArea_2Year: 0,
	}
}

func openSearchCustomerDetail2pbDetail(item *opensearch_remote.CustomerDetail) *pb.CustomerDetail {
	if item == nil {
		return nil
	}

	if item.TopCompanyName == item.CompanyName {
		//如果顶级公司就是本体，则不返回顶级公司数据
		item.TopCompanyName = ""
		item.TopCompanyOrganizingCode = ""
	}
	result := &pb.CustomerDetail{
		CompanyName:                      item.CompanyName,
		CompanyNameHl:                    item.CompanyNameHL,
		OldCompanyNameHl:                 item.OldCompanyNameHL,
		OrganizingCode:                   item.OrganizingCode,
		CompanyLogo:                      item.DeveloperLogo,
		BusinessStatusLabel:              item.BusinessStatusLabel,
		TopCompanyName:                   item.TopCompanyName,
		TopCompanyOrganizingCode:         item.TopCompanyOrganizingCode,
		CompanyType:                      item.CompanyType,
		Province:                         item.Province,
		City:                             item.City,
		ProvinceCode:                     item.ProvinceCode,
		CityCode:                         item.CityCode,
		LegalName:                        item.LegalName,
		EstablishDate:                    strings.Split(item.EstablishDate, " ")[0],
		IndustryCategory:                 item.IndustryCategorySmall,
		BidCnt_2Year:                     item.BidCnt2Year,
		TakeLandCnt_2Year:                item.TakeLandCnt2Year,
		CommencePermitCnt_2Year:          item.CommencePermitCnt2Year,
		SellProjectCnt_2Year:             item.SellProjectCnt2Year,
		CooperationCaseCnt_2Year:         item.CooperationCaseCnt2Year,
		ContactNum:                       item.ContactNum,
		Telephone:                        item.PhoneNumber,
		BidCnt_1Year:                     item.BidCnt1Year,
		TakeLandCnt_1Year:                item.TakeLandCnt1Year,
		CommencePermitCnt_1Year:          item.CommencePermitCnt1Year,
		SellProjectCnt_1Year:             item.SellProjectCnt1Year,
		CooperationCaseCnt_1Year:         item.CooperationCaseCnt1Year,
		Scope:                            item.Scope,
		EnterpriseNature:                 item.EnterpriseNature,
		TermStart:                        strings.Split(item.TermStart, " ")[0],
		TermEnd:                          strings.Split(item.TermEnd, " ")[0],
		NumberOfEmployees:                item.NumberOfEmployees,
		Address:                          item.Address,
		BidNum:                           item.BidNum,
		ProjectNum:                       item.TakeLandCnt + item.CommencePermitCnt + item.SellProjectCnt,
		TakeLandNum:                      item.TakeLandCnt,
		CommencePermitNum:                item.CommencePermitCnt,
		SellProjectNum:                   item.SellProjectCnt,
		CooperationEnterpriseNum:         item.CooperationEnterpriseNum,
		CooperationProjectNum:            item.CooperationProjectNum,
		CompanyProfile:                   item.CompanyProfile,
		EsScore:                          int32(item.Score),
		CreditLevel:                      item.CreditLevelLabel,
		ProjectNameHl:                    item.ProjectNameHL,
		BidCntWithArea_2Year:             item.BidCntWithArea2Year,
		LandCntWithArea_2Year:            item.LandCntWithArea2Year,
		CommencePermitCntWithArea_2Year:  item.CommencePermitCntWithArea2Year,
		CooperationCaseCntWithArea_2Year: item.CooperationCaseCntWithArea2Year,
		SellProjectCntWithArea_2Year:     item.SellProjectCntWithArea2Year,
	}
	if item.RegistCapi > 0 && item.RegistCapiUnit != "" {
		result.RegistCapi = fmt.Sprintf("%02.2f%s", item.RegistCapi, item.RegistCapiUnit)
	}
	if item.RecCapi > 0 && item.RecCapiUnit != "" {
		result.RecCapi = fmt.Sprintf("%02.2f%s", item.RecCapi, item.RecCapiUnit)
	}

	if item.CustomerDynamic.TypeName != "" {
		result.CustomerDynamic = &pb.CustomerDynamicItem{
			TypeName: item.CustomerDynamic.TypeName,
			Date:     item.CustomerDynamic.Date,
			Title:    item.CustomerDynamic.Title,
		}
	}

	if item.IsDeveloper == 1 {
		result.CompanyIdentity = append(result.CompanyIdentity, constants.CompanyIdentityDeveloper)
	}
	if item.IsSupplier == 1 {
		result.CompanyIdentity = append(result.CompanyIdentity, constants.CompanyIdentitySupplier)
	}

	// 拼接logo
	if item.DeveloperId != "" && !strings.HasPrefix(result.CompanyLogo, "http") {
		result.CompanyLogo = utils.GetCompanyLogoUrl(item.DeveloperId, item.DeveloperLogo)
	}

	for _, labelItem := range item.CompanyLabelArr {
		result.CompanyLabel = append(result.CompanyLabel, &pb.CustomerLabel{
			Label:  labelItem.Name,
			Remark: constants.GetCompanyLabelRemark(labelItem.Name),
		})
	}
	for _, labelItem := range item.CompanyLevelArr {
		result.CompanyLevel = append(result.CompanyLevel, &pb.CustomerLabel{
			Label:  labelItem.Name,
			Remark: constants.GetCompanyLabelRemark(labelItem.Name),
		})
	}

	return result
}

func (s *businessCustomerService) GetCustomerDetail(ctx context.Context, request *pb.GetCustomerDetailRequest) (*pb.GetCustomerDetailResponse, error) {
	resp := &pb.GetCustomerDetailResponse{}
	detailList, err := s.openSearchRepos.GetCustomerDetail(ctx, &opensearch_remote.GetCustomerDetailRequest{OrganizingCodes: request.OrganizingCode})
	if err != nil {
		return nil, err
	}

	if len(detailList) == 0 {
		//主档案不存在该社会信用代码，则将该企业添加到反哺任务中
		detail, _ := s.openApiRepo.GetCompanyDetail(ctx, request.OrganizingCode)
		if detail != nil && detail.OrganizingCode == request.OrganizingCode {
			_, err = s.openApiRepo.AddSyncTask(ctx, []string{detail.CompanyName})
			stark.Logger.Infof(ctx, "客户详情主档案不存在，添加到反哺任务，社会信用代码:%s,公司名称:%s,添加反哺任务错误信息:%+v",
				request.OrganizingCode, detail.CompanyName, err)
			resp.Detail = openapiCustomerDetail2pbDetail(detail)
		} else {
			return nil, ykerrcode.TogRPCError(errcode.CustomerNotExistError, "客户详情不存在")
		}
	}

	for _, detail := range detailList {
		if detail.OrganizingCode == request.OrganizingCode {
			resp.Detail = openSearchCustomerDetail2pbDetail(detail)
			resp.Detail.IndustryCategory = fmt.Sprintf("%s/%s/%s", detail.IndustryCategoryBig, detail.IndustryCategoryMiddle, detail.IndustryCategorySmall)
		}
	}

	// 获取商机查看状态，获取是否已经存在客户池
	if resp.Detail != nil {
		metaUserInfo := usermetadata.GetMetaUserInfo(ctx)
		opptyStatusPo, _ := s.opptyStatusRepos.GetOpptyStatus(ctx, constants.OpptySourceCustomer, resp.Detail.OrganizingCode, metaUserInfo.TenantUserUid)
		if opptyStatusPo != nil && opptyStatusPo.Id != 0 {
			resp.Detail.OpptyStatus = constants.GetOpptyNameByStatus(opptyStatusPo.Status)
		} else {
			_ = s.opptyStatusRepos.SaveOpptyStatus(ctx, &opptyStatusRepo.GfyxOpptyStatus{
				Status:       constants.OpptyStatusView,
				DataSource:   constants.OpptySourceCustomer,
				DataSourceId: request.OrganizingCode,
				UserGuid:     metaUserInfo.TenantUserUid,
			})
		}

		count, _, _ := s.customerRepo.QueryCustomerList(ctx, map[string]interface{}{"organizing_code": resp.Detail.OrganizingCode}, nil)
		if count > 0 {
			resp.Detail.IsExistCustomer = true
		}
	}
	return resp, nil
}

func (s *businessCustomerService) GetCustomerDetailBatch(ctx context.Context, organizingCodes []string) ([]*opensearch_remote.CustomerDetail, error) {
	detailList, err := s.openSearchRepos.GetCustomerDetail(ctx, &opensearch_remote.GetCustomerDetailRequest{OrganizingCodes: strings.Join(organizingCodes, ",")})
	if err != nil {
		return nil, err
	}
	return detailList, nil
}

func (s *businessCustomerService) GetSupplierProject(ctx context.Context, request *pb.GetSupplierProjectRequest) (*pb.GetSupplierProjectResponse, error) {
	bigDataRequest := &bigdata_remote.SupplierProjectRequest{
		Page:           request.Page,
		PageSize:       request.PageSize,
		OrganizingCode: request.OrganizingCode,
		AreaCode:       request.AreaCode,
		CoopTimeMax:    request.CoopTimeMax,
		CoopTimeMin:    request.CoopTimeMin,
	}
	if request.Keyword != "" {
		bigDataRequest.Keyword = "%" + request.Keyword + "%"
	}
	SupplierProjectResponse, err := s.bigDataServiceRepo.GetSupplierProject(ctx, bigDataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata GetSupplierProject request:%#v, err:%s", bigDataRequest, err.Error())
		return nil, err
	}
	result := &pb.GetSupplierProjectResponse{}
	if SupplierProjectResponse == nil {
		return result, nil
	}

	for _, item := range SupplierProjectResponse.List {
		data := &pb.SupplierProject{
			Id:                item.Id,
			CoopAmount:        item.CoopAmount,
			CoopAmountOrgin:   item.CoopAmountOrgin,
			CoopCity:          item.CoopCity,
			CoopCityCode:      item.CoopCityCode,
			OrganizingCode:    item.OrganizingCode,
			CoopCompanyCode:   item.CoopCompanyCode,
			CoopCompanyName:   item.CoopCompanyName,
			CoopEndTime:       item.CoopEndTime,
			CoopStartTime:     item.CoopStartTime,
			CoopPrjName:       item.CoopPrjName,
			CoopProjectType:   item.CoopProjectType,
			CoopProvince:      item.CoopProvince,
			CoopProvinceCode:  item.CoopProvinceCode,
			DataSource:        item.DataSource,
			SupplierId:        item.SupplierId,
			SupplierName:      item.SupplierName,
			SubSupplierName:   item.SubSupplierName,
			SubOrganizingCode: item.SubOrganizingCode,
			SourceId:          item.SourceId,
		}
		if data.CoopStartTime != "" && len(data.CoopStartTime) >= 10 {
			data.CoopStartTime = data.CoopStartTime[0:10]
		}
		result.List = append(result.List, data)
	}
	result.Total = SupplierProjectResponse.Total

	return result, nil
}

// GetFeed 客户动态
func (s *businessCustomerService) GetFeed(ctx context.Context, request *pb.GetFeedRequest) (*pb.GetFeedResponse, error) {
	bigDataRequest := &bigdata_remote.GetFeedRequest{
		OrganizingCode: request.OrganizingCode,
		Page:           request.Page,
		PageSize:       request.PageSize,
	}
	bigDataFeedResponse, err := s.bigDataServiceRepo.GetFeed(ctx, bigDataRequest)
	if err != nil {
		stark.Logger.Error(ctx, "bigdata GetFeed,err:%s", err.Error())
	}
	result := &pb.GetFeedResponse{}
	if bigDataFeedResponse == nil {
		return result, nil
	}

	for _, item := range bigDataFeedResponse.List {
		data := &pb.GetFeed{}
		simplecopier.CopyToStruct(data, item)
		result.List = append(result.List, data)
	}
	result.Total = bigDataFeedResponse.Total
	return result, nil
}

func (s *businessCustomerService) GetInvestCompany(ctx context.Context, request *pb.GetInvestCompanyRequest) (*pb.GetInvestCompanyResponse, error) {
	bigDataRequest := &bigdata_remote.GetInvestCompanyRequest{
		OrganizingCode: request.OrganizingCode,
		PageNum:        1,
		PageSize:       10000, //设置1w加股权公司，可修改
	}

	bigDataInvestCompanyResponse, err := s.bigDataServiceRepo.GetInvestCompany(ctx, bigDataRequest)
	if err != nil {
		stark.Logger.Error(ctx, "bigdata GetInvestCompany,err:%s", err.Error())
	}
	result := &pb.GetInvestCompanyResponse{}
	if bigDataInvestCompanyResponse == nil {
		return result, nil
	}

	for _, item := range bigDataInvestCompanyResponse.List {
		data := &pb.GetInvestCompany{}
		data.OrganizingCode = item.SubOrganizingCode
		data.CompanyName = item.SubCompanyName
		data.ParentOrganizingCode = item.SubParentOrganizingCode
		data.Percent = item.ParentPercent
		result.List = append(result.List, data)
	}
	return result, nil
}

// FuzzySearch 模糊搜索公司
func (s *businessCustomerService) FuzzySearch(ctx context.Context, request *pb.FuzzySearchCustomerRequest) (*pb.FuzzySearchCustomerResponse, error) {
	resp := &pb.FuzzySearchCustomerResponse{}
	searchData, err := s.openSearchRepos.FuzzySearch(ctx, &opensearch_remote.FuzzySearchRequest{Keyword: request.Keyword})
	if err != nil {
		return nil, err
	}
	for _, item := range searchData {
		resp.List = append(resp.List, &pb.FuzzySearchCustomerItem{
			CompanyName:      item.CompanyName,
			CompanyNameHl:    item.CompanyNameHl,
			OldCompanyNameHl: item.OldCompanyNameHl,
		})
	}
	return resp, nil
}

func (s *businessCustomerService) GetCompanyTarget(ctx context.Context, companyName []string) []*bigdata_remote.GetCompanyTargetItem {
	if len(companyName) <= 0 {
		return make([]*bigdata_remote.GetCompanyTargetItem, 0)
	}
	bigdataRequest := &bigdata_remote.GetCompanyTargetRequest{
		CompanyName: companyName,
	}
	getCompanyContactCntResponse, err := s.bigDataServiceRepo.GetCompanyTarget(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata GetCompanyTarget,err:%s", err.Error())
	}
	return getCompanyContactCntResponse.List
}

func (s *businessCustomerService) GetCustomerZxList(ctx context.Context, request *pb.GetCustomerRiskCommonRequest) (*pb.GetCustomerZxListResponse, error) {
	respData, err := s.openApiRepo.GetCompanyZxList(ctx, &openapi_remote.GetCompanyRiskCommonRequest{
		Keyword:       request.Keyword,
		IsReturnTotal: 1,
		PageNum:       request.PageNum,
		PageSize:      request.PageSize,
	})
	if err != nil {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	resp := &pb.GetCustomerZxListResponse{}
	if respData != nil {
		resp.Total = respData.Total
		for _, item := range respData.Items {
			resp.List = append(resp.List, &pb.CustomerZxListItem{
				CaseDate:   item.CaseDate,
				CaseNo:     item.CaseNo,
				ExecuteGov: item.ExecuteGov,
				Biaodi:     item.Biaodi,
			})
		}
	}
	return resp, nil
}

func (s *businessCustomerService) GetCustomerCourtRegister(ctx context.Context, request *pb.GetCustomerRiskCommonRequest) (*pb.GetCustomerCourtRegisterResponse, error) {
	respData, err := s.openApiRepo.GetCompanyCourtRegister(ctx, &openapi_remote.GetCompanyRiskCommonRequest{
		Keyword:       request.Keyword,
		IsReturnTotal: 1,
		PageNum:       request.PageNum,
		PageSize:      request.PageSize,
	})
	if err != nil {
		return nil, err
	}
	resp := &pb.GetCustomerCourtRegisterResponse{}
	if respData != nil {
		resp.Total = respData.Total
		for _, item := range respData.Items {
			resp.List = append(resp.List, &pb.CustomerCourtRegister{
				Litigant:    item.Litigant,
				Plaintiff:   item.Plaintiff,
				Defendant:   item.Defendant,
				CompanyName: item.SupplierName,
				CaseType:    item.CaseType,
				CaseStatus:  item.CaseStatus,
				CaseNo:      item.CaseNo,
				Court:       item.Court,
				FilingDate:  item.FilingDate,
				CaseReason:  item.CaseReason,
			})
		}
	}
	return resp, nil
}

func (s *businessCustomerService) GetCustomerLawSuit(ctx context.Context, request *pb.GetCustomerRiskCommonRequest) (*pb.GetCustomerLawSuitResponse, error) {
	respData, err := s.openApiRepo.GetCompanyLawSuit(ctx, &openapi_remote.GetCompanyRiskCommonRequest{
		Keyword:       request.Keyword,
		IsReturnTotal: 1,
		PageNum:       request.PageNum,
		PageSize:      request.PageSize,
	})
	if err != nil {
		return nil, err
	}
	resp := &pb.GetCustomerLawSuitResponse{}
	if respData != nil {
		resp.Total = respData.Total
		for _, item := range respData.Items {
			resp.List = append(resp.List, &pb.CustomerLawSuit{
				Title:        item.Title,
				CompanyName:  item.SupplierName,
				LawsuitUrl:   item.LawsuitUrl,
				LawsuitH5Url: item.LawsuitH5Url,
				Court:        item.Court,
				DocType:      item.DocType,
				CaseType:     item.CaseType,
				SubmitTime:   item.SubmitTime,
				JudgeTime:    item.JudgeTime,
				CaseReason:   item.CaseReason,
			})
		}
	}
	return resp, nil
}

func (s *businessCustomerService) GetCustomerTaxIllegal(ctx context.Context, request *pb.GetCustomerRiskCommonRequest) (*pb.GetCustomerTaxIllegalResponse, error) {
	respData, err := s.openApiRepo.GetCompanyTaxIllegalList(ctx, &openapi_remote.GetCompanyRiskCommonRequest{
		Keyword:       request.Keyword,
		IsReturnTotal: 1,
		PageNum:       request.PageNum,
		PageSize:      request.PageSize,
	})
	if err != nil {
		return nil, err
	}
	resp := &pb.GetCustomerTaxIllegalResponse{}
	if respData != nil {
		resp.Total = respData.Total
		for _, item := range respData.Items {
			resp.List = append(resp.List, &pb.CustomerTaxIllegal{
				OperName:          item.OperName,
				CompanyName:       item.SupplierName,
				OrganizingCode:    item.OrgCode,
				Address:           item.Address,
				CaseNature:        item.CaseNature,
				IllegalContent:    item.IllegalContent,
				IllegalTime:       item.IllegalTime,
				AgencyCompanyName: item.AgencyCompanyName,
			})
		}
	}
	return resp, nil
}

func (s *businessCustomerService) GetCustomerRiskCount(ctx context.Context, request *pb.GetCustomerRiskCountRequest) (*pb.GetCustomerRiskCountResponse, error) {
	respData, err := s.openApiRepo.GetCompanyRiskCount(ctx, &openapi_remote.GetCompanyRiskCountRequest{
		Keyword: request.Keyword,
		TabCodes: []string{
			"QccGetSupplierZX",
			"QccGetSupplierCourtRegister",
			"QccGetSupplierLawSuit",
			"QccGetSupplierRelaTaxIllegal",
		},
	})
	if err != nil {
		return nil, err
	}
	resp := &pb.GetCustomerRiskCountResponse{}
	if respData != nil {
		for _, item := range respData.Items {
			switch item.Tab {
			case "QccGetSupplierZX":
				resp.ZxListCount = item.Value
			case "QccGetSupplierCourtRegister":
				resp.CourtRegisterCount = item.Value
			case "QccGetSupplierLawSuit":
				resp.LawSuitCount = item.Value
			case "QccGetSupplierRelaTaxIllegal":
				resp.TaxIllegalCount = item.Value
			}
		}
	}
	return resp, nil
}

func (s *businessCustomerService) GetCustomerScore(ctx context.Context, request *pb.GetCustomerScoreRequest) ([]*pb.GetCustomerScoreResponse, error) {
	if request == nil || len(request.OrganizingCode) == 0 {
		return nil, nil
	}

	landUsage, projectType := "", ""
	// 如果接口参数没有传土地类型和在建项目类型，那么查询一次数据库
	if len(request.SubscriptionLandUsage) == 0 && len(request.SubscriptionProjectType) == 0 {
		metaUserInfo := usermetadata.GetMetaUserInfo(ctx)
		radarSubscriptionConfig, _ := s.radarSubscriptionConfigRepos.GetRadarSubscriptionConfigByUser(ctx, metaUserInfo.TenantUserUid)
		if radarSubscriptionConfig != nil {
			landUsage = radarSubscriptionConfig.LandUsage
			projectType = radarSubscriptionConfig.BuildingType
		}
	} else {
		landUsage = strings.Join(request.SubscriptionLandUsage, ",")
		projectType = strings.Join(request.SubscriptionProjectType, ",")
	}

	customerScoreResp := customerDto.GetCustomerScoreResponse{}
	//1.调用数芯接口获取得分明细
	bigDataClient := http_client.NewBigdataApiHttpClient()
	_, _, errs := bigDataClient.Post(ctx, constants.GetCustomerScoreUri,
		map[string]interface{}{"organizing_codes": request.OrganizingCode}, nil).EndStruct(&customerScoreResp)
	if len(errs) > 0 {
		return nil, errs[0]
	}

	if len(customerScoreResp.Data) == 0 {
		return nil, nil
	}
	//2.调用opensearch接口，计算得分
	developerScoreList, err := s.openSearchRepos.GetDeveloperScore(ctx, &opensearch_remote.GetCustomerScoreRequest{
		OrganizingCode:          request.OrganizingCode,
		SubscriptionLandUsage:   landUsage,
		SubscriptionProjectType: projectType,
	})
	if err != nil {
		return nil, err
	}
	if len(developerScoreList) == 0 {
		return nil, nil
	}

	type tmpStd struct {
		scoreData   *opensearch_remote.GetCustomerScoreData
		scoreDetail *customerDto.ScoreDetail
	}
	//3.汇总1和2的数据，结构化返回
	organizingCodeMap := make(map[string]tmpStd)
	for _, scoreData := range developerScoreList {
		st, ok := organizingCodeMap[scoreData.OrganizingCode]
		if ok {
			st.scoreData = scoreData
			organizingCodeMap[scoreData.OrganizingCode] = st
		} else {
			organizingCodeMap[scoreData.OrganizingCode] = tmpStd{scoreData: scoreData, scoreDetail: nil}
		}
	}
	for _, scoreDetail := range customerScoreResp.Data {
		st, ok := organizingCodeMap[scoreDetail.OrganizingCode]
		if ok {
			st.scoreDetail = scoreDetail
			organizingCodeMap[scoreDetail.OrganizingCode] = st
		} else {
			organizingCodeMap[scoreDetail.OrganizingCode] = tmpStd{scoreData: nil, scoreDetail: scoreDetail}
		}
	}

	var result []*pb.GetCustomerScoreResponse
	for _, std := range organizingCodeMap {
		if std.scoreData != nil && std.scoreDetail != nil {
			result = append(result, assembleScore(std.scoreData, std.scoreDetail))
		}
	}

	return result, nil
}

func assembleScore(item *opensearch_remote.GetCustomerScoreData, scoreDetail *customerDto.ScoreDetail) *pb.GetCustomerScoreResponse {
	takeLandPriceStr, projectInvestStr := "", ""
	if scoreDetail.TakeLandPrice2Year < 10000 {
		takeLandPriceStr = fmt.Sprintf("%d万元", scoreDetail.TakeLandPrice2Year)
	} else {
		takeLandPriceStr = fmt.Sprintf("%d.%d亿元", scoreDetail.TakeLandPrice2Year/10000, scoreDetail.TakeLandPrice2Year/100%100)
	}

	if scoreDetail.ProjectInvest2Year < 10000 {
		projectInvestStr = fmt.Sprintf("%d万元", scoreDetail.ProjectInvest2Year)
	} else {
		projectInvestStr = fmt.Sprintf("%d.%d亿元", scoreDetail.ProjectInvest2Year/10000, scoreDetail.ProjectInvest2Year/100%100)
	}

	customerScoreItem := &pb.GetCustomerScoreResponse{
		OrganizingCode: item.OrganizingCode,
		TotalScore:     int32(item.DeveloperScore),
		UpdatedTime:    scoreDetail.PulsarTime,
		InvestmentAmount: &pb.ScoreDetail{
			Score:    int32(scoreDetail.InvestModuleScore),
			MaxScore: int32(scoreDetail.InvestModuleScoreUpperLimit),
			Detail: []string{fmt.Sprintf("近两年拿地<span>%d</span>块，总投资金额<span>%s</span>", scoreDetail.TakeLandCtn2Year, takeLandPriceStr),
				fmt.Sprintf("近两年在建<span>%d</span>个，总投资金额<span>%s</span>", scoreDetail.ProjectCtn2Year, projectInvestStr)},
		},
		ReturnOfFund: &pb.ScoreDetail{
			Score:    int32(scoreDetail.RecoveriesModuleScore),
			MaxScore: int32(scoreDetail.RecoveriesModuleScoreUpperLimit),
			Detail: []string{fmt.Sprintf("近两年开盘<span>%d</span>个，总套数<span>%d</span>套",
				scoreDetail.BuildingSetsCnt, scoreDetail.NewhouseCnt2Year)},
		},
		CreditScore: &pb.ScoreDetail{
			Score:    int32(scoreDetail.CreditModuleScore),
			MaxScore: int32(scoreDetail.CreditModuleScoreUpperLimit),
			Detail:   nil,
		},
		MatchDemand: &pb.ScoreDetail{
			Score:    int32(item.MatchRequirementModuleScore),
			MaxScore: int32(scoreDetail.MatchRequirementModuleScoreUpperLimit),
			Detail: []string{fmt.Sprintf("匹配需求的土地类型<span>%d</span>块", item.MatchRequirementLandCtn),
				fmt.Sprintf("匹配需求的在建项目<span>%d</span>个", item.MatchRequirementProjectCtn)},
		},
		AnnualIncrease: &pb.ScoreDetail{
			Score:    int32(scoreDetail.AnnualIncreaseModuleScore),
			MaxScore: int32(scoreDetail.AnnualIncreaseModuleScoreUpperLimit),
			Detail:   nil,
		},
	}

	//信用得分明细
	creditScoreDetail := ""
	if scoreDetail.IndustryCategoryBig != "" {
		creditScoreDetail += "当前公司所属<span>" + scoreDetail.IndustryCategoryBig + "</span>行业"
	}
	if scoreDetail.ZxRecordCnt2Year > 0 {
		if creditScoreDetail != "" {
			creditScoreDetail += "，近两年<span>存在</span>被执行人"
		} else {
			creditScoreDetail = "当前公司近两年<span>存在</span>被执行人"
		}
	} else {
		if creditScoreDetail != "" {
			creditScoreDetail += "，近两年<span>不存在</span>被执行人"
		} else {
			creditScoreDetail = "当前公司近两年<span>不存在</span>被执行人"

		}
	}
	if creditScoreDetail != "" {
		customerScoreItem.CreditScore.Detail = append(customerScoreItem.CreditScore.Detail, creditScoreDetail)
	}

	creditScoreDetail = ""
	if scoreDetail.TopCompanyIndustryCategoryBig != "" {
		creditScoreDetail += "当前公司的顶级公司所属<span>" + scoreDetail.IndustryCategoryBig + "</span>行业"
	}
	if scoreDetail.TopCompanyZxRecordCnt2Year > 0 {
		if creditScoreDetail != "" {
			creditScoreDetail += "，近两年<span>存在</span>被执行人"
		} else {
			creditScoreDetail = "当前公司的顶级公司近两年<span>存在</span>被执行人"

		}
	} else {
		if creditScoreDetail != "" {
			creditScoreDetail += "，近两年<span>不存在</span>被执行人"
		} else {
			creditScoreDetail = "当前公司的顶级公司近两年<span>不存在</span>被执行人"

		}
	}
	if creditScoreDetail != "" {
		customerScoreItem.CreditScore.Detail = append(customerScoreItem.CreditScore.Detail, creditScoreDetail)
	}

	//年度增长明细
	takeLandDetail := ""
	if scoreDetail.TakeLandYoy < 0 {
		takeLandDetail = fmt.Sprintf("土地储备年度同比减少<span>%.0f%%</span>", scoreDetail.TakeLandYoy*-100)
	} else {
		takeLandDetail = fmt.Sprintf("土地储备年度同比增长<span>%.0f%%</span>", scoreDetail.TakeLandYoy*100)
	}

	projectDetail := ""
	if scoreDetail.ProjectYoy < 0 {
		projectDetail = fmt.Sprintf("在建项目年度同比减少<span>%.0f%%</span>", scoreDetail.ProjectYoy*-100)
	} else {
		projectDetail = fmt.Sprintf("在建项目年度同比增长<span>%.0f%%</span>", scoreDetail.ProjectYoy*100)
	}

	//newHouseDetail := ""
	//if scoreDetail.NewhouseYoy < 0 {
	//	newHouseDetail = fmt.Sprintf("新开盘项目年度同比减少<span>%.0f%%</span>", scoreDetail.NewhouseYoy*-100)
	//} else {
	//	newHouseDetail = fmt.Sprintf("新开盘项目年度同比增长<span>%.0f%%</span>", scoreDetail.NewhouseYoy*100)
	//}
	customerScoreItem.AnnualIncrease.Detail = append(customerScoreItem.AnnualIncrease.Detail, takeLandDetail, projectDetail)

	return customerScoreItem
}

func (s *businessCustomerService) GetCustomerCommencePermitList(ctx context.Context, request *pb.GetCustomerCommencePermitRequest) (*pb.GetCustomerCommencePermitResponse, error) {
	bigDataRequest := &customerDto.BigDataCommencePermitListRequest{
		PageNum:           request.Page,
		PageSize:          request.PageSize,
		OrganizingCode:    request.OrganizingCode,
		SubOrganizingCode: request.SubOrganizingCode,
		ProvinceCode:      request.ProvinceCode,
		CityCode:          request.CityCode,
	}

	bigDataCommencePermitListResponse := &customerDto.BigDataCommencePermitListResponse{}
	bigDataRequestMap, _ := simplecopier.StructToMapByJsonTag(bigDataRequest)
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.GetCustomerCommencePermitEquity, bigDataRequestMap, map[string]string{}).EndStruct(bigDataCommencePermitListResponse)
	if len(errs) > 1 {
		stark.Logger.Error(ctx, "获取数芯接口", constants.GetCustomerCommencePermitEquity, "异常,err:", errs[0])
		return nil, errs[0]
	}

	result := &pb.GetCustomerCommencePermitResponse{}

	for _, item := range bigDataCommencePermitListResponse.Data.Rows {
		data := &pb.CommencePermit{
			Id:                item.Id,
			ProjectName:       item.ProjectName,
			PrjNum:            item.PrjNum,
			DeveloperName:     item.SubDeveloperName,
			OrganizingCode:    item.OrganizingCode,
			Province:          item.Province,
			ProvinceCode:      item.ProvinceCode,
			City:              item.City,
			CityCode:          item.CityCode,
			SubDeveloperName:  item.SubDeveloperName,
			SubOrganizingCode: item.SubOrganizingCode,
			PrjFunctionNum:    item.PrjFunctionNum,
			IsPriceGtAvg:      item.IsPriceGtAvg,
			UpdateTime:        item.UpdateTime,
		}
		result.List = append(result.List, data)
	}
	result.Total = bigDataCommencePermitListResponse.Data.TotalNum

	return result, nil

}

// GetExportCustomerTotal  导出找客户列表获取总记录数
func (s *businessCustomerService) GetExportCustomerTotal(ctx context.Context, condition interface{}) (total int64, err error) {
	var request *pb.SearchCustomerListRequest
	switch condition.(type) {
	case *pb.SearchCustomerListRequest:
		request = condition.(*pb.SearchCustomerListRequest)
	case string:
		request = &pb.SearchCustomerListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "找客户获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	// 获取总条目，只需要取一条数据就好了
	searchRequest := &opensearch_remote.GetCustomerListRequest{
		Keyword:             request.Keyword,
		CompanyNameKeyword:  request.CompanyNameKeyword,
		CompanyIdentity:     request.CompanyIdentity,
		CompanyArea:         request.AreaCodes,
		CompanyLevel:        request.CompanyLevel,
		CompanyLabel:        request.CompanyLabel,
		CompanyType:         request.CompanyType,
		IndustryCategory:    request.IndustryCategory,
		LandUsageLabel:      request.LandUsageLabel,
		ProjectTypeLabel:    request.ProjectTypeLabel,
		FitmentFeeLabel:     request.FitmentFeeLabel,
		BiddingArea:         request.BiddingArea,
		CreditLevel:         request.CreditLevel,
		ProjectProvinceCode: request.ProjectProvinceCode,
		ProjectCityCode:     request.ProjectCityCode,
		ProjectBeginDate:    request.ProjectBeginDate,
		ProjectEndDate:      request.ProjectEndDate,
		Page:                1,
		PageSize:            1,
	}
	searchData, err := s.openSearchRepos.GetCustomerList(ctx, searchRequest)
	if err != nil {
		return
	}

	if searchData == nil {
		return
	}

	total = int64(searchData.Total)
	return
}

// QueryExportCustomerBatchData 导出客户列表，分批获取数据
func (s *businessCustomerService) QueryExportCustomerBatchData(ctx context.Context, condition interface{}, batchNum, batchSize int32) (rowTitle []string, rowData [][]string, err error) {
	rowTitle = strings.Split(constants.OrderTypeCustomerExportFields, "，")
	var request *pb.SearchCustomerListRequest
	switch condition.(type) {
	case *pb.SearchCustomerListRequest:
		request = condition.(*pb.SearchCustomerListRequest)
	case string:
		request = &pb.SearchCustomerListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "找客户获取导出数据错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	default:
		err = errors.New("导出客户列表，查询条件错误")
	}

	searchRequest := &opensearch_remote.GetCustomerListRequest{
		Keyword:             request.Keyword,
		CompanyNameKeyword:  request.CompanyNameKeyword,
		CompanyIdentity:     request.CompanyIdentity,
		CompanyArea:         request.AreaCodes,
		CompanyLevel:        request.CompanyLevel,
		CompanyLabel:        request.CompanyLabel,
		CompanyType:         request.CompanyType,
		IndustryCategory:    request.IndustryCategory,
		LandUsageLabel:      request.LandUsageLabel,
		ProjectTypeLabel:    request.ProjectTypeLabel,
		FitmentFeeLabel:     request.FitmentFeeLabel,
		BiddingArea:         request.BiddingArea,
		CreditLevel:         request.CreditLevel,
		ProjectProvinceCode: request.ProjectProvinceCode,
		ProjectCityCode:     request.ProjectCityCode,
		ProjectBeginDate:    request.ProjectBeginDate,
		ProjectEndDate:      request.ProjectEndDate,
		Page:                batchNum,
		PageSize:            batchSize,
	}
	searchData, err := s.openSearchRepos.GetCustomerList(ctx, searchRequest)
	if err != nil {
		return
	}

	if searchData == nil {
		return
	}

	for _, item := range searchData.List {
		registerCap := ""
		if item.RegistCapi > 0 && item.RegistCapiUnit != "" {
			registerCap = fmt.Sprintf("%02.2f%s", item.RegistCapi, item.RegistCapiUnit)
		}

		var label []string
		for _, companyLabel := range item.CompanyLabelArr {
			label = append(label, companyLabel.Name)
		}
		for _, companyLevel := range item.CompanyLevelArr {
			label = append(label, companyLevel.Name)
		}

		// 顶级公司是自己，就不展示
		if item.TopCompanyName == item.CompanyName {
			item.TopCompanyName = ""
		}

		rowData = append(rowData, []string{
			item.CompanyName,    //公司名称
			item.OrganizingCode, //社会统一信用代码
			item.CompanyType,    //公司类型
			item.LegalName,      //企业法人
			registerCap,         //注册资本
			strings.Split(item.EstablishDate, " ")[0],       //成立日期
			item.IndustryCategorySmall,                      //所在行业
			item.BusinessStatusLabel,                        //经营状态
			item.Scope,                                      //经营范围
			item.Address,                                    //公司地址
			fmt.Sprintf("%s%s", item.Province, item.City),   //注册地区
			item.NumberOfEmployees,                          //公司规模
			item.TopCompanyName,                             //顶级公司
			fmt.Sprintf("%d", item.TakeLandCnt1Year),        //近1年拿地
			fmt.Sprintf("%d", item.TakeLandCnt2Year),        //近2年拿地
			fmt.Sprintf("%d", item.CommencePermitCnt1Year),  //近1年在建项目
			fmt.Sprintf("%d", item.CommencePermitCnt2Year),  //近2年在建项目
			fmt.Sprintf("%d", item.SellProjectCnt1Year),     //近1年开盘
			fmt.Sprintf("%d", item.SellProjectCnt2Year),     //近2年开盘
			fmt.Sprintf("%d", item.BidCnt1Year),             //近1年采购招标
			fmt.Sprintf("%d", item.BidCnt2Year),             //近2年采购招标
			fmt.Sprintf("%d", item.CooperationCaseCnt1Year), //近1年合作单位
			fmt.Sprintf("%d", item.CooperationCaseCnt2Year), //近2年合作单位
			//客户标签
			strings.Join(label, "，"),
		})
	}

	return
}

// GetExportSupplierProjectTotal  导出客户详情-合作案例获取总记录数
func (s *businessCustomerService) GetExportSupplierProjectTotal(ctx context.Context, condition interface{}) (total int64, err error) {
	var request *pb.GetSupplierProjectRequest
	switch condition.(type) {
	case *pb.GetSupplierProjectRequest:
		request = condition.(*pb.GetSupplierProjectRequest)
	case string:
		request = &pb.GetSupplierProjectRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "客户详情-开盘列表获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	// 获取总条目，只需要取一条数据就好了
	bigDataRequest := &bigdata_remote.SupplierProjectRequest{
		Page:           1,
		PageSize:       1,
		OrganizingCode: request.OrganizingCode,
		AreaCode:       request.AreaCode,
		CoopTimeMax:    request.CoopTimeMax,
		CoopTimeMin:    request.CoopTimeMin,
	}
	if request.Keyword != "" {
		bigDataRequest.Keyword = "%" + request.Keyword + "%"
	}
	searchData, err := s.bigDataServiceRepo.GetSupplierProject(ctx, bigDataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata GetSupplierProject request:%#v, err:%s", bigDataRequest, err.Error())
		return 0, err
	}
	if searchData == nil {
		return
	}

	total = int64(searchData.Total)
	return
}

// QueryExportSupplierProjectBatchData 导出客户详情-合作案例列表，分批获取数据
func (s *businessCustomerService) QueryExportSupplierProjectBatchData(ctx context.Context, condition interface{}, batchNum, batchSize int32) (rowTitle []string, rowData [][]string, err error) {
	rowTitle = strings.Split(constants.OrderTypeCustomerDetailCaseExportFields, "，")
	var request *pb.GetSupplierProjectRequest
	switch condition.(type) {
	case *pb.GetSupplierProjectRequest:
		request = condition.(*pb.GetSupplierProjectRequest)
	case string:
		request = &pb.GetSupplierProjectRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "客户详情-合作案例列表获取导出记录数据错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	// 获取总条目，只需要取一条数据就好了
	bigDataRequest := &bigdata_remote.SupplierProjectRequest{
		Page:           batchNum,
		PageSize:       batchSize,
		OrganizingCode: request.OrganizingCode,
		AreaCode:       request.AreaCode,
		CoopTimeMax:    request.CoopTimeMax,
		CoopTimeMin:    request.CoopTimeMin,
	}
	if request.Keyword != "" {
		bigDataRequest.Keyword = "%" + request.Keyword + "%"
	}
	searchData, err := s.bigDataServiceRepo.GetSupplierProject(ctx, bigDataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata GetSupplierProject request:%#v, err:%s", bigDataRequest, err.Error())

	}
	if searchData == nil {
		return
	}
	for _, item := range searchData.List {
		area := ""
		if item.CoopProvince == item.CoopCity {
			area = item.CoopProvince
		} else {
			area = fmt.Sprintf("%s%s", item.CoopProvince, item.CoopCity)
		}
		rowData = append(rowData, []string{
			item.CoopPrjName, //案例名称，
			area,             //案例地区，
			strings.Split(item.CoopStartTime, " ")[0], //合作时间，
			fmt.Sprintf("%s万元", item.CoopAmount),      //合作金额，
			item.CoopCompanyName,                      //甲方单位，
			item.SubSupplierName,                      //合作单位
		})
	}

	return
}
